package com.kingbook.core.sql;

import com.kingbook.common.security.DigestsManager;
import com.kingbook.common.utils.StringUtils;
import com.kingbook.core.cache.CacheConfig;

import java.util.List;
import java.util.Map;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
public class SqlContext {

    protected String namespace;

    protected String sqlId;

    protected String key;

    protected String sql;

    protected List<String> tableNames;

    protected Map<String, ?> paramMap;

    protected CacheConfig cacheConfig;

    SqlContext() {
    }

    SqlContext(String sql, List<String> tableNames) {
        this.sql = sql;
        this.tableNames = tableNames;
    }

    SqlContext(String sql, List<String> tableNames, CacheConfig cacheConfig) {
        this("default", "default", sql, tableNames, null, cacheConfig);
    }

    public SqlContext(String namespace, String sqlId, String sql, List<String> tableNames, Map<String, ?> paramMap, CacheConfig cacheConfig) {
        this.namespace = namespace;
        this.sqlId = sqlId;
        this.sql = sql;
        this.tableNames = tableNames;
        this.paramMap = paramMap;
        this.cacheConfig = cacheConfig;
    }

    public String genKey(Class clazz) {
        if(StringUtils.isEmpty(key)) {
            StringBuilder sb = new StringBuilder(sql);
            if (paramMap != null) {
                paramMap.forEach((k, v) -> {
                    sb.append("&").append(k).append("&").append(v);
                });
            }
            sb.append(clazz.getName());
            key = namespace + ":" + sqlId + ":" + DigestsManager.md5(sb.toString().getBytes());
        }
        return key;
    }

    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    public String getSqlId() {
        return sqlId;
    }

    public void setSqlId(String sqlId) {
        this.sqlId = sqlId;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public Map<String, ?> getParamMap() {
        return paramMap;
    }

    public void setParamMap(Map<String, ?> paramMap) {
        this.paramMap = paramMap;
    }

    public List<String> getTableNames() {
        return tableNames;
    }

    public void setTableNames(List<String> tableNames) {
        this.tableNames = tableNames;
    }

    public CacheConfig getCacheConfig() {
        return cacheConfig;
    }

    public void setCacheConfig(CacheConfig cacheConfig) {
        this.cacheConfig = cacheConfig;
    }
}
